package com.glory.wxelectricitypda.activity;

import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.adapter.AddCarrierDataAdapter;
import com.glory.wxelectricitypda.adapter.DefectDataAdapter;
import com.glory.wxelectricitypda.adapter.ItemBomInfoAdapter;
import com.glory.wxelectricitypda.adapter.ItemMTConsumeAdapter;
import com.glory.wxelectricitypda.base.App;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.ConsumeListEntity;
import com.glory.wxelectricitypda.bean.DefectCodeBean;
import com.glory.wxelectricitypda.bean.LotBean;
import com.glory.wxelectricitypda.bean.MTConsumeEntity;
import com.glory.wxelectricitypda.bean.NewTrackOutBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class NewTrackOutActivity extends BaseDialogActivity {


    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.tvCarryId)
    TextView tvCarryId;
    @BindView(R.id.tvAddBadCode)
    TextView tvAddBadCode;
    @BindView(R.id.etQty)
    FreeUI_ClearEditText etQty;
    @BindView(R.id.rvDefectCodeList)
    RecyclerView rvDefectCodeList;
    @BindView(R.id.flCode)
    FrameLayout flCode;
    @BindView(R.id.tvCode)
    TextView tvCode;
    @BindView(R.id.ivCode)
    ImageView ivCode;
    @BindView(R.id.etItemCount)
    FreeUI_ClearEditText etItemCount;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.tvLotNum)
    TextView tvLotNum;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.etMaterielModel)
    FreeUI_ClearEditText etMaterielModel;
    @BindView(R.id.rvBomList)
    RecyclerView rvBomList;
    @BindView(R.id.rbYes)
    RadioButton rbYes;
    @BindView(R.id.rbNo)
    RadioButton rbNo;
    @BindView(R.id.etRemark)
    FreeUI_ClearEditText etRemark;
    @BindView(R.id.etEndNum)
    FreeUI_ClearEditText etEndNum;
    @BindView(R.id.llEnd)
    LinearLayout llEnd;
    @BindView(R.id.tvPartName)
    TextView tvPartName;
    @BindView(R.id.tvAttribute1)
    TextView tvAttribute1;
    @BindView(R.id.llGoodsShelves)
    LinearLayout llGoodsShelves;
    @BindView(R.id.etUser)
    FreeUI_ClearEditText etUser;
    @BindView(R.id.etGoodsShelves)
    FreeUI_ClearEditText etGoodsShelves;

    private FreeUI_GeneralFragmentDialog addCarryIdDialog;
    private DefectDataAdapter mDefectDataAdapter;
    private FreeUI_GeneralPop mCodePop;
    private int postion = 0;
    private ArrayList<String> codeList = new ArrayList<>();
    private ArrayList<String> descList = new ArrayList<>();
    private AddCarrierDataAdapter materielModelAdapter;
    private ItemMTConsumeAdapter mItemMTConsumeAdapter;
    private ArrayList<LotBean.ScrapcoDescBean> scrapcoDescBeans;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_trackout_new;
    }

    @Override
    protected void initView() {
        freeUI_titleView.setTitle("出站");
        freeUI_titleView.setRightListener("提交", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (etLotId.getText().toString().equals("")) {
                    showToast("请扫描批次号", false);
                    return;
                }
                if (llEnd.getVisibility() == View.VISIBLE) {
                    if (etEndNum.getText().toString().equals("") || etEndNum.getText().toString().equals("0")) {
                        showToast("请输入剩余数量", false);
                        return;
                    }
                }
                JSONObject map = new JSONObject();
                try {
                    map.put("LotID", etLotId.getText().toString());
//                    map.put("CarrierList", tvCarryId.getText().toString());
                    map.put("CarrierList", materielModelAdapter.getData().toString().replace("[", "").replace("]", "").replace(" ", "").replace(",", ";"));
                    map.put("NumberOfBars", etItemCount.getText().toString());
                    map.put("LotComment", etRemark.getText().toString());
                    map.put("RESERVED2", etGoodsShelves.getText().toString());
                    map.put("GRADE2", etItemCount.getText().toString());
                    map.put("IsLastLot", rbYes.isChecked());
                    if (llEnd.getVisibility() == View.VISIBLE) {
                        map.put("LastAmount", Integer.parseInt(etEndNum.getText().toString()));
                    }
//                    map.put("ScrapList", new JsonParser().parse(new Gson().toJson(mDefectDataAdapter.getData())).getAsJsonArray());
                    map.put("ScrapList", new JSONArray(new Gson().toJson(mDefectDataAdapter.getData())));
                    ArrayList<MTConsumeEntity> mtConsumeEntities = new ArrayList<>();
                    for (ConsumeListEntity.ConsumeListDTO datum : mItemMTConsumeAdapter.getData()) {
                        MTConsumeEntity mtConsumeEntity = new MTConsumeEntity();
                        mtConsumeEntity.setConsume(Integer.parseInt(datum.getConsume().equals("") ? "0" : datum.getConsume()));
                        mtConsumeEntity.setMLotId(datum.getMlotid());
                        mtConsumeEntity.setMType(datum.getMaterialtype());
                        mtConsumeEntity.setMTType(datum.getMttype());
                        mtConsumeEntity.setPosition(datum.getPosition());
                        mtConsumeEntity.setMCode(datum.getMaterialname());
                        mtConsumeEntities.add(mtConsumeEntity);
                    }
                    map.put("XLotList", new JSONArray(new Gson().toJson(mtConsumeEntities)));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                NetUtils.requestPostUtils("trackOut", "TrackOut", map, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                        new TypeToken<ResponseBean<LotBean>>() {
                        }.getType(), getSupportFragmentManager(), this) {
                    @Override
                    public void onSuccess(Response<ResponseBean<LotBean>> response) {
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            showToast("出站成功", true);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                }
                            }, 2000);
                        }
                    }

                    @Override
                    public void onError(Response<ResponseBean<LotBean>> response) {
                        super.onError(response);
                        loadError(response.getException(), "TrackOut");
                    }
                });
            }
        });
        rvDefectCodeList.setLayoutManager(new LinearLayoutManager(this));
        rvDefectCodeList.setItemAnimator(new DefaultItemAnimator());
        rvDefectCodeList.addItemDecoration(new DividerItemDecoration(this, 1));
        mDefectDataAdapter = new DefectDataAdapter(null);
        mDefectDataAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mDefectDataAdapter.isFirstOnly(true);
        rvDefectCodeList.setAdapter(mDefectDataAdapter);


        rvMaterielModelList.setLayoutManager(new LinearLayoutManager(this));
        rvMaterielModelList.setItemAnimator(new DefaultItemAnimator());
        rvMaterielModelList.addItemDecoration(new DividerItemDecoration(this, 1));
        materielModelAdapter = new AddCarrierDataAdapter(null, getSupportFragmentManager());
        materielModelAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielModelAdapter.isFirstOnly(true);
        rvMaterielModelList.setAdapter(materielModelAdapter);
//        getScrapcodeList("M230303011-03");

        rvBomList.setLayoutManager(new LinearLayoutManager(this));
        rvBomList.setItemAnimator(new DefaultItemAnimator());
        rvBomList.addItemDecoration(new DividerItemDecoration(this, 1));
        mItemMTConsumeAdapter = new ItemMTConsumeAdapter(null);
        mItemMTConsumeAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mItemMTConsumeAdapter.isFirstOnly(true);
        rvBomList.setAdapter(mItemMTConsumeAdapter);

    }

    @Override
    protected void initData() {

        etLotId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    codeList.clear();
                    descList.clear();
                    mItemMTConsumeAdapter.setNewData(null);
                    String userName = etUser.getText().toString();
                    if (userName.isEmpty()) {
                        showToast("请输入操作人工号", false);
                        return;
                    }
                    requestUser(userName, new CallBack() {
                        @Override
                        public void success() {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("LotID", s.toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            NetUtils.requestPostUtils("getLotInfo", "GetLotInfo", jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<NewTrackOutBean>>(
                                    new TypeToken<ResponseBean<NewTrackOutBean>>() {
                                    }.getType(), getSupportFragmentManager(), this) {
                                @Override
                                public void onSuccess(Response<ResponseBean<NewTrackOutBean>> response) {
                                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {

                                        tvStep.setText(response.body().getBody().getLOT().getSTEPDESC());
                                        tvLotNum.setText(String.valueOf(response.body().getBody().getLOT().getMAINQTY()));
                                        etItemCount.setText(response.body().getBody().getLOT().getCOUNTBARS());
                                        tvAttribute1.setText(response.body().getBody().getLOT().getATTRIBUTE1());
                                        tvPartName.setText(response.body().getBody().getLOT().getPARTNAME());
                                        String workStep = response.body().getBody().getLOT().getSTEPNAME();
                                        String track_out_wizard = response.body().getBody().getSTEP().getTRACK_OUT_WIZARD();
                                        if (track_out_wizard.equals("EuitDieBondingTrackOut")){
                                            llEnd.setVisibility(View.VISIBLE);
                                            rbNo.setChecked(true);
                                            etEndNum.setText(tvLotNum.getText().toString());
                                            etEndNum.setClearIconVisible(false);
                                            etEndNum.setEnabled(false);
                                        }else {
                                            llEnd.setVisibility(View.GONE);
                                            rbNo.setChecked(true);
                                            etEndNum.setText("");
                                        }
                                        switch (workStep) {
                                            case "A202":
                                            case "A201":
                                                break;
                                            case "A308":
                                                llGoodsShelves.setVisibility(View.VISIBLE);
                                                break;
                                            default:
                                                llGoodsShelves.setVisibility(View.GONE);
                                                break;
                                        }



//                                        tvStep.setText(response.body().getBody().getLotInfo().getSTEPDESC());
//                                        tvLotNum.setText(response.body().getBody().getLotInfo().getMAINQTY());
//                                        etItemCount.setText(response.body().getBody().getLotInfo().getCOUNTBARS());
//                                        tvAttribute1.setText(response.body().getBody().getLotInfo().getATTRIBUTE1());
//                                        tvPartName.setText(response.body().getBody().getLotInfo().getPARTNAME());
//                                        String workStep = response.body().getBody().getLotInfo().getSTEPNAME();
//                                        switch (workStep) {
//                                            case "A202":
//                                            case "A201":
//                                                llEnd.setVisibility(View.VISIBLE);
//                                                break;
//                                            case "A308":
//                                                llGoodsShelves.setVisibility(View.VISIBLE);
//                                                break;
//                                            default:
//                                                llEnd.setVisibility(View.GONE);
//                                                llGoodsShelves.setVisibility(View.GONE);
//                                                break;
//                                        }
                                        getScrapcodeList(s.toString());
                                    }
                                }
                                @Override
                                public void onError(Response<ResponseBean<NewTrackOutBean>> response) {
                                    super.onError(response);
                                    loadError(response.getException(), "GetLotInfo");
                                }
                            });
                        }
                        @Override
                        public void fail() {
                            showToast("操作人工号验证失败，请重新输入", false);
                        }
                        @Override
                        public void error() {
                            showToast("连接不到服务器，请重试", false);
                        }
                    });
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        initEdit(etMaterielModel, s -> {
            if (materielModelAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }
            materielModelAdapter.getData().add(s);
            materielModelAdapter.notifyDataSetChanged();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    etMaterielModel.setText("");
                    etMaterielModel.requestFocus();
                }
            }, 500);
        });

        rbYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etEndNum.setText("");
                etEndNum.setClearIconVisible(true);
                etEndNum.setEnabled(true);
            }
        });
        rbNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etEndNum.setText(tvLotNum.getText().toString());
                etEndNum.setClearIconVisible(false);
                etEndNum.setEnabled(false);
            }
        });
    }

    private void getScrapcodeList(String lotid) {

        JSONObject map = new JSONObject();
        try {
            map.put("LotID", lotid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostUtils("getScrapcodeList", "GetScrapcodeList", map, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    scrapcoDescBeans = response.body().getBody().getSCRAPCODES();
                    for (LotBean.ScrapcoDescBean scrapcode : response.body().getBody().getSCRAPCODES()) {
                        codeList.add(scrapcode.getCODE());
                        descList.add(scrapcode.getDESCRIPTION());
                    }
                    getEqpAllConsume(lotid);
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "GetScrapcodeList");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    @OnClick({R.id.rlCarryId, R.id.flCode, R.id.tvAddBadCode,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rlCarryId:
                addCarryIdDialog = FreeApi_DialogUtils.getScanDialog(this, "请扫描载具编号", new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        String carryIds = tvCarryId.getText().toString().trim();
                        boolean isSame = false;
                        if (carryIds.length() == 0) {
                            tvCarryId.setText(s);
                        } else {
                            if (carryIds.contains(";")) {
                                String[] array = carryIds.split(";");
                                for (String str : array) {
                                    if (str.equals(s)) {
                                        isSame = true;
                                    }
                                }
                            } else {
                                if (carryIds.equals(s)) {
                                    isSame = true;
                                }
                            }
                            if (isSame) {
                                showToast("载具编号不能重复", false);
                            } else {
                                StringBuffer stringBuffer = new StringBuffer();
                                stringBuffer.append(carryIds);
                                stringBuffer.append(";");
                                stringBuffer.append(s);
                                tvCarryId.setText(stringBuffer.toString());
                            }
                        }
                        addCarryIdDialog.dismiss();
                    }
                });
                addCarryIdDialog.show(getSupportFragmentManager(), "addCarryIdDialog");
                break;
            case R.id.flCode:
                if (mCodePop != null) {
                    if (mCodePop.isShowing()) {
                        mCodePop.dismiss();
                    }
                } else {
                    mCodePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCode.getWidth(), descList, ivCode, codeS -> {
                        tvCode.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivCode);
                mCodePop.showAsDropDown(flCode, 0, 0);
                break;
            case R.id.tvAddBadCode:
                if (scrapcoDescBeans == null){
                    showToast("未获取到不良代码", false);
                    return;
                }
                if (etLotId.getText().toString().equals("")) {
                    showToast("请先扫描批次ID", false);
                    return;
                }
                if (tvCode.getText().toString().equals("")) {
                    showToast("请选择不良代码", false);
                    return;
                }
                if (etQty.getText().toString().equals("")) {
                    showToast("请输入数量", false);
                    return;
                }
                DefectCodeBean defectCodeListBean = new DefectCodeBean();
                for (LotBean.ScrapcoDescBean scrapcoDescBean : scrapcoDescBeans) {
                    if (scrapcoDescBean.getDESCRIPTION().equals(tvCode.getText().toString())){
                        defectCodeListBean.setCODE(scrapcoDescBean.getCODE());
                    }
                }
                defectCodeListBean.setACTIONDESC(tvCode.getText().toString());
                defectCodeListBean.setQTY(Integer.parseInt(etQty.getText().toString()));

                if (containCode(defectCodeListBean)) {
                    mDefectDataAdapter.addData(defectCodeListBean);
                } else {
                    FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmAndCancelDialog(App.app, "是", "否", "当前列表已添加，是否重复添加", () -> {
                        mDefectDataAdapter.addData(defectCodeListBean);
                    }, () -> {
                    });
                    tipDialog.show(getSupportFragmentManager(), "DIALOG");
                }
                break;
        }
    }

    private boolean containCode(DefectCodeBean scrapEntity) {
        for (DefectCodeBean bean : mDefectDataAdapter.getData()) {
            if (bean.getCODE().equals(scrapEntity.getCODE())) {
                return false;
            }
        }
        return true;
    }

    private void getEqpAllConsume(String lotID) {
        JSONObject map = new JSONObject();
        try {
            map.put("LotID", lotID);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostUtils("getEqpAllConsume", "GetEqpAllConsume", map, this, new FreeUI_DialogEntityCallBack<ResponseBean<ConsumeListEntity>>(
                new TypeToken<ResponseBean<ConsumeListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<ConsumeListEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    mItemMTConsumeAdapter.setNewData(response.body().getBody().getConsumeList());
                }
            }

            @Override
            public void onError(Response<ResponseBean<ConsumeListEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "GetEqpAllConsume");
            }
        });
    }
}
